package com.laf.web.controller.common;

import cn.hutool.core.util.StrUtil;
import com.google.code.kaptcha.Producer;
import com.laf.common.config.LafConfig;
import com.laf.common.constant.CacheConstants;
import com.laf.common.constant.Constants;
import com.laf.common.core.domain.AjaxResult;
import com.laf.common.core.domain.R;
import com.laf.common.core.redis.RedisCache;
import com.laf.common.enums.SMSTypeEnum;
import com.laf.common.exception.ServiceException;
import com.laf.common.utils.SMSUtil;
import com.laf.common.utils.sign.Base64;
import com.laf.common.utils.uuid.IdUtils;
import com.laf.manage.domain.dto.CheckSmsCodeDTO;
import com.laf.system.service.ISysConfigService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 验证码操作处理
 *
 * @author ruoyi
 */
@Slf4j
@RestController
@Api(tags = "验证码管理")
@RequiredArgsConstructor
public class CaptchaController
{
    @Resource(name = "captchaProducer")
    private Producer captchaProducer;

    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;

    private final RedisCache redisCache;

    private final ISysConfigService configService;

    private final SMSUtil smsUtil;

    /**
     * 生成验证码
     */
    @GetMapping("/captchaImage")
    @ApiOperation("获取验证码")
    public AjaxResult getCode(HttpServletResponse response) throws IOException
    {
        AjaxResult ajax = AjaxResult.success();
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        ajax.put("captchaEnabled", captchaEnabled);
        if (!captchaEnabled)
        {
            return ajax;
        }

        // 保存验证码信息
        String uuid = IdUtils.simpleUUID();
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;

        String capStr = null, code = null;
        BufferedImage image = null;

        // 生成验证码
        String captchaType = LafConfig.getCaptchaType();
        if ("math".equals(captchaType))
        {
            String capText = captchaProducerMath.createText();
            capStr = capText.substring(0, capText.lastIndexOf("@"));
            code = capText.substring(capText.lastIndexOf("@") + 1);
            image = captchaProducerMath.createImage(capStr);
        }
        else if ("char".equals(captchaType))
        {
            capStr = code = captchaProducer.createText();
            image = captchaProducer.createImage(capStr);
        }

        redisCache.setCacheObject(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try
        {
            ImageIO.write(image, "jpg", os);
        }
        catch (IOException e)
        {
            return AjaxResult.error(e.getMessage());
        }

        ajax.put("uuid", uuid);
        ajax.put("img", Base64.encode(os.toByteArray()));
        return ajax;
    }




    /**
     * 发送验证码短信
     */
    @GetMapping("/register/sendSms")
    @ApiOperation(value = "注册账号发送短信")
    public R sendSms(String phone) {
        if (StrUtil.isBlank(phone)) throw new ServiceException("手机号不能为空");
        String code = smsUtil.sendSms(phone, SMSTypeEnum.REGISTER);
        log.info("发送短信验证码 - 注册：" + code);
        return R.ok();
    }

    @GetMapping("/pwd/sendSms")
    @ApiOperation(value = "忘记密码发送短信")
    public R forgetPwdSendSms(String phone) {
        if (StrUtil.isBlank(phone)) throw new ServiceException("手机号不能为空");
        String code = smsUtil.sendSms(phone, SMSTypeEnum.FORGET_PASSWORD);
        log.info("发送短信验证码 - 忘记密码：" + code);
        return R.ok();
    }

    @PostMapping("/check/smsCode")
    @ApiOperation(value = "校验修改密码的验证码")
    public R checkSmsCode(@RequestBody @Validated CheckSmsCodeDTO dto) {
        smsUtil.checkSms(dto.getPhone(), dto.getCode(), SMSTypeEnum.FORGET_PASSWORD);
        return R.ok();
    }
}
